package com.ydlclass.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.net.InetSocketAddress;

@Component
public class IpFilter implements GlobalFilter, Ordered {


    //写业务逻辑
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        黑客ip直接拒绝
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String hostAddress = remoteAddress.getAddress().getHostAddress();
        System.out.println(hostAddress);



        if (hostAddress.equals("1.1.1.1")){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            Mono<Void> voidMono = response.setComplete();
            return voidMono;
        }

        //走完了  该到下一个过滤器
        return chain.filter(exchange);
    }

    //返回数值  越小越先执行
    @Override
    public int getOrder() {
        return 0;
    }
}
